package com.example.demo.singlecase;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 3、懒汉模式-线程不安全（线程不安全）【不可用】
 * 
 * 这种写法起到了Lazy Loading的效果，但是只能在单线程下使用。如果在多线程下，一个线程进入了if (singleton == null)判断语句块，
 * 还未来得及往下执行，另一个线程也通过了这个判断语句，这时便会产生多个实例。所以在多线程环境下不可使用这种方式。
 * @author chenjie
 *
 */
public class Singleton3 {
	private static Singleton3 singleton;
	private static int count =0;
	private static final CountDownLatch countDownLatch =new CountDownLatch(30000);
	private Singleton3() {
		count++;
	}
	public static Singleton3 getInstance() {
		//System.out.println("线程："+Thread.currentThread().getName());
		if(singleton==null) {
			singleton=new Singleton3();
		}
		return singleton;
	}
	
	public static void main(String[] args) {
		for(int j=0;j<1000;j++) {
		ExecutorService executorService=Executors.newCachedThreadPool();
		for(int i=0;i<30000;i++) {
			executorService.execute(()->{
//				getInstance();
				Singleton8.INSTANCE.whateverMethod();
				countDownLatch.countDown();
			});
		}
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("count:"+count);
		}
	}
}
